package com.jdy.hotel.net.callback;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.jdy.hotel.net.DataSource;
import com.jdy.hotel.net.ResponseData;
import com.jdy.hotel.net.ResponseDataListener;
import com.jdy.hotel.utils.L;
import com.zhy.http.okhttp.callback.StringCallback;

import java.net.SocketTimeoutException;

import okhttp3.Call;

public class BaseCallback extends StringCallback implements DataSource<ResponseData> {

    private final ResponseDataListener<ResponseData> listener;

    public BaseCallback(ResponseDataListener<ResponseData> listener) {
        this.listener = listener;
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        L.i("请求失败  ID ： %d,   Exception : %s", id, e);
        if (e instanceof SocketTimeoutException) {
            respond(ResponseData.error(ResponseData.DEFAULT_REQUEST_ERROR_CODE, ResponseData.SERVER_CONNECT_TIMEOUT + e.getMessage()));
        } else
            respond(ResponseData.error(e.getMessage()));
    }

    @Override
    public void onResponse(String response, int id) {
        L.i("响应结果! ID ： %d,   Exception : %s ", id, response);

        if (TextUtils.isEmpty(response)) {
            //如果没有请求到数据
            onError(null, new NullPointerException("Have not any element!"), id);
        }

        try {
            respond(new Gson().fromJson(response, ResponseData.class));
        } catch (Exception e) {
            onError(null, e, id);
        }
    }

    @Override
    public void respond(ResponseData result) {
        if (listener != null) listener.onRespond(result);
    }

}
